# data_inserter.py
import pymysql


class DataInserter:
    INSERT_SQL = """
    INSERT INTO purchase_exchange_batch (
        company_id, plan_id, plan_name, date, tran_batch_no, payment_account_id,
        pay_act_no, payee_act_no, total_amt, total_cost, total_fee, total_tax_cny,
        currency, estimate_rate, purchase_rate, pay_amt, total_cnt, state,
        finished_time, create_time, update_time, delete_time, sell_amount
    ) VALUES (
        %(company_id)s, %(plan_id)s, %(plan_name)s, %(date)s, %(tran_batch_no)s, %(payment_account_id)s,
        %(pay_act_no)s, %(payee_act_no)s, %(total_amt)s, %(total_cost)s, %(total_fee)s, %(total_tax_cny)s,
        %(currency)s, %(estimate_rate)s, %(purchase_rate)s, %(pay_amt)s, %(total_cnt)s, %(state)s,
        %(finished_time)s, %(create_time)s, %(update_time)s, %(delete_time)s, %(sell_amount)s
    )
    """

    @staticmethod
    def insert_records(cursor, records):
        """向数据库插入多条记录"""
        success_count = 0
        duplicate_count = 0

        for record in records:
            try:
                cursor.execute(DataInserter.INSERT_SQL, record)
                success_count += 1
            except pymysql.IntegrityError as e:
                if e.args[0] == 1062:  # 唯一键冲突
                    duplicate_count += 1
                else:
                    raise

        return success_count, duplicate_count